package com.dianrui.moonfire.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.os.Build;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.adapter.RegularAdapter;
import com.dianrui.moonfire.alipay.PayResult;
import com.dianrui.moonfire.bean.Regular;
import com.dianrui.moonfire.event.GetPartABitmap;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.NoDoubleClickUtils;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.dianrui.moonfire.view.CountDownButton;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:合作申请
 * User: luoziyin
 * Date: 2020-8-17
 */
@SuppressWarnings("ALL")
public class CooperationActivity extends BaseActivity {
    private boolean mInputflag = false;
    private String mContracts;
    private List<Regular> regularsList = new ArrayList<>();
    private RegularAdapter regularAdapter;
    private String months;
    private ImageView imgPartA;
    private AlertDialog dialog;


    @BindView(R.id.regular)
    LinearLayout regulars;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.franchise_contract_txt)
    TextView franchiseContractTxt;//易行加盟合同
    @BindView(R.id.signup_clause_choose)
    CheckBox signupClauseChoose;
    @BindView(R.id.money_result)
    TextView moneyResult;
    @BindView(R.id.car_numbers)
    EditText carNumbers;
    @BindView(R.id.show_name)
    EditText showName;
    @BindView(R.id.mobile)
    EditText mobile;
    @BindView(R.id.countdown)
    CountDownButton countdown;
    @BindView(R.id.show_code)
    EditText showCode;
    @BindView(R.id.car_price_ed)
    EditText carPriceEd;
    @BindView(R.id.show_auth_code)
    EditText showAuthCode;
    @BindView(R.id.listview)
    ListView listView;


    @Override
    public int getContentViewId() {
        return R.layout.activity_cooperation;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(true);
        title.setText(getString(R.string.coopertion_title));
        franchiseContractTxt.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        franchiseContractTxt.getPaint().setAntiAlias(true);
        regularAdapter = new RegularAdapter(CooperationActivity.this, regularsList);
        listView.setAdapter(regularAdapter);
        carNumbers.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mInputflag || TextUtils.isEmpty(s.toString())) {
                    moneyResult.setText("(0.00)");
                    return;
                }
                if ("0".equals(s.toString())) {
                    ToastUtil.showToast(getString(R.string.vehicles_put_least_one));
                    carNumbers.setText("");
                    moneyResult.setText("(0.00)");
                    return;
                }
                mInputflag = true;
                Float number = Float.valueOf(carNumbers.getText().toString());
                Float price = Float.valueOf(carPriceEd.getText().toString().replace("车辆单价：", "").replace("元/辆", ""));
                float result = number * price;
                moneyResult.setText("(" + MyUtil.formatBy2Float(result, 2) + ")");
                mInputflag = false;
            }
        });
        countdown.setOnOperationCallBack(new CountDownButton.CountDownButtonOperationCallBack() {
            @Override
            public void onFinish() {
                countdown.millisInFuture(60000);
                countdown.setText(getString(R.string.login_txt2));
                countdown.setTextColor(ContextCompat.getColor(CooperationActivity.this, R.color.gray_FF959595));
            }

            @Override
            public void onTick(long millisUntilFinished, CountDownButton countDownButton) {
                String tickTxts = millisUntilFinished / 1000 + getString(R.string.getcode_txt4);
                countdown.setText(tickTxts);
                countdown.setTextColor(ContextCompat.getColor(CooperationActivity.this, R.color.gray_FF959595));
            }

            @Override
            public void onClickFromUser(boolean isRunning, long millisUntilFinished, CountDownButton countDownButton) {
                getVerificationCode();
            }
        });
        getContractMemberInfo();
        regularAdapter.setOnButtonClickListener(new RegularAdapter.RegularClickListener() {
            @Override
            public void onRegularClick(int position, String name) {
                for (int i = 0; i < regularsList.size(); i++) {
                    if (position == i) {
                        regularsList.get(position).isChecked = false;
                    }
                }
                regularsList.get(position).isChecked = true;
                months = name;
                regularAdapter.notifyDataSetChanged();
            }
        });
        mobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(mobile.getWindowToken(), 0);
                    }


                }
            }
        });
        showCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 6) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(showCode.getWindowToken(), 0);
                    }
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GetPartABitmap partBitmap) {
        imgPartA.setImageBitmap(partBitmap.bitmap);
    }

    @SuppressLint("SetTextI18n")
    private void getContractMemberInfo() {
        XHttpRequest.getInstance().postWithMemberToken(Url.CONTRACT_MEMBER, "", new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                carPriceEd.setText(getString(R.string.price_of_vehicle) + jsonObject.optJSONObject("data").optString("price") + getString(R.string.yuan_vehicle));
                                JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("regular");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        Regular regular = new Regular();
                                        regular.title = jsonArray.optJSONObject(i).optString("title");
                                        regular.name = jsonArray.optJSONObject(i).optString("name");
                                        regular.type = jsonArray.optJSONObject(i).optString("type");
                                        regular.money = jsonArray.optJSONObject(i).optString("money");
                                        regularsList.add(regular);
                                    }
                                    if (regularAdapter != null) {
                                        regularAdapter.refresh(regularsList);
                                    }
                                    regulars.setVisibility(View.VISIBLE);
                                    listView.setVisibility(View.VISIBLE);
                                } else {
                                    regulars.setVisibility(View.GONE);
                                    listView.setVisibility(View.GONE);
                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                SPUtils.getInstance().clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpKillActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });


    }



    /**
     * 获取验证码
     */
    public void getVerificationCode() {
        if (StringUtils.isEmpty(mobile.getText().toString())) {
            ToastUtil.showToast(getString(R.string.coopertion_mobile_hint));
            return;
        }
        if (mobile.getText().length() < 11) {
            ToastUtil.showToast(getString(R.string.mobile_number_must_be_11_digits));
            return;
        }

        if (countdown.getmCurrentmillis() > 2000) {
            ToastUtil.showToast(countdown.getmCurrentmillis() / 1000 + getString(R.string.getcode_txt4));
            return;
        }
        showLoadingDialog(getString(R.string.send_sms));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("account", mobile.getText().toString().trim());
        /**验证类型：1登录/注册，2修改绑定手机，3代理商获取验证码，4申请合同签约**/
        jsonObject.addProperty("type", "4");
        XHttpRequest.getInstance().postRequests(Url.GETCODE, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                countdown.start();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                dismissLoadingDialog();
                                countdown.cancel();
                                countdown.setText(getString(R.string.getcode_txt));
                                countdown.setTextColor(ContextCompat.getColor(CooperationActivity.this, R.color.gray_FF959595));
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                countdown.cancel();
                countdown.setText(getString(R.string.getcode_txt));
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public void initData() {
    }


    @OnClick({R.id.back, R.id.signup_payment, R.id.franchise_contract_txt})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.signup_payment:
                if (StringUtils.isEmpty(showName.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.coopertion_name_hint));
                    return;
                }
                if (StringUtils.isEmpty(mobile.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.coopertion_mobile_hint));
                    return;
                }
                if (StringUtils.isEmpty(showCode.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.login_txt3));
                    return;
                }
                if (StringUtils.isEmpty(showAuthCode.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.coopertion_auth_code_hint));
                    return;
                }
                if (StringUtils.isEmpty(carNumbers.getText().toString().trim())) {
                    ToastUtil.showToast(getString(R.string.vehicles_put_least_one));
                    return;
                }
                if (!signupClauseChoose.isChecked()) {
                    ToastUtil.showToast(getString(R.string.agree_franchise_contract));
                    return;
                }
                if (StringUtils.isEmpty(months)) {
                    ToastUtil.showToast(getString(R.string.choose_income));
                    return;
                }
                if (StringUtils.isEmpty(mContracts)) {
                    ToastUtil.showToast(getString(R.string.please_sign));
                    return;
                }
                submitCoopetion();
                break;
            case R.id.franchise_contract_txt:
                showAgreementDialog();
                break;

            default:
                break;
        }
    }

    @SuppressLint("InflateParams")
    //显示合约的对话框
    private void showAgreementDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(CooperationActivity.this, R.style.RcDialogs);
        final View view1 = LayoutInflater.from(CooperationActivity.this).inflate(R.layout.dialog_write_sign, null);
        imgPartA = view1.findViewById(R.id.parta);
        final CheckBox arrangementCb = view1.findViewById(R.id.franchise_arrangement_choose);
        final LinearLayout linearLayout = view1.findViewById(R.id.line);
        final TextView clickSign = view1.findViewById(R.id.click_sign);
        imgPartA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    if (!arrangementCb.isChecked()) {//必须同意才能签名,签名功能见LinePathView类
                        ToastUtil.showToast(getString(R.string.youmustsign));
                        return;
                    }
                    startActivity(new Intent(CooperationActivity.this, WriteSignActivity.class));
                }

            }
        });
        final Button save = view1.findViewById(R.id.save);
        //保存以pdf格式保存在本地
        save.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                save.setVisibility(View.GONE);
                clickSign.setVisibility(View.GONE);
                PdfDocument document = new PdfDocument();
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
                        linearLayout.getMeasuredWidth(), linearLayout.getMeasuredHeight(), 1).create();
                PdfDocument.Page page = document.startPage(pageInfo);
                linearLayout.draw(page.getCanvas());
                document.finishPage(page);
                try {
                    String path = "/storage/emulated/0/yh_agreement.pdf";
                    File e = new File(path);
                    if (e.exists()) {
                        e.delete();
                    }
                    document.writeTo(new FileOutputStream(e));
                    //将保存的pdf转化为base64
                    mContracts = MyUtil.PDFToBase64(e);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog = builder.create();
        dialog.setView(view1);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    //提交合约申请
    private void submitCoopetion() {
        showLoadingDialog(getString(R.string.submitting_contract_application));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("mobile", mobile.getText().toString().trim());
        jsonObject.addProperty("name", showName.getText().toString().trim());
        jsonObject.addProperty("card", showAuthCode.getText().toString().trim());
        jsonObject.addProperty("number", carNumbers.getText().toString().trim());
        jsonObject.addProperty("verify_code", showCode.getText().toString().trim());
        jsonObject.addProperty("contract", mContracts);
        jsonObject.addProperty("month", months);
        jsonObject.addProperty("type", "2");
        XHttpRequest.getInstance().postWithMemberToken(Url.SUBMIT_COOPERTION, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                String data = JsonUtils.getJsonStr(response, "data");
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                //需要交一定的费用
                                createPayDialog(JsonUtils.getJsonStr(data, "ids"), JsonUtils.getJsonStr(data, "money"));
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(JsonUtils.getJsonStr(response, "message"));
                            }
                        }
                    } catch (JSONException e) {
                        dismissLoadingDialog();
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });


    }

    private void createPayDialog(final String ids, final String money) {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(CooperationActivity.this);
        View view = LayoutInflater.from(CooperationActivity.this).inflate(R.layout.dialog_pays, null);
        Button pay = view.findViewById(R.id.pay);
        ImageView close = view.findViewById(R.id.close);
        LinearLayout clickZfb = view.findViewById(R.id.click_zfb);
        LinearLayout clickWx = view.findViewById(R.id.click_wx);
        TextView showMoney = view.findViewById(R.id.show_dialog_money);
        final CheckBox cbZfb = view.findViewById(R.id.cb_zfb);
        final CheckBox cbWx = view.findViewById(R.id.cb_wx);
        String showMoneys = money;

        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(MyUtil.formatBy2Float(Float.parseFloat(money),2));
        showMoney.setText(stringBuilder.toString());

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog.dismiss();
            }
        });
        clickZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(true);
                cbWx.setChecked(false);
            }
        });
        clickWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
            }
        });
        cbZfb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(true);
                cbWx.setChecked(false);
            }
        });
        cbWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
            }
        });
        pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cbWx.isChecked()) {
                    bottomSheetDialog.dismiss();
                    payWx(money, ids);
                } else if (cbZfb.isChecked()) {
                    bottomSheetDialog.dismiss();
                    payszfb(money, ids);
                }
            }
        });
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCancelable(false );
        bottomSheetDialog.setCanceledOnTouchOutside(false);
        bottomSheetDialog.show();

    }

    private void payWx(String money, String ids) {
        JsonObject payJson = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            payJson.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        payJson.addProperty("payment_mode", "2");
        payJson.addProperty("money", money);
        payJson.addProperty("type", "33");
        payJson.addProperty("ids", ids);
        XHttpRequest.getInstance().postRequests(Url.PAY, payJson.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                IWXAPI msgApi = WXAPIFactory.createWXAPI(CooperationActivity.this, Constant.WXAppID, true);
                                if (!msgApi.isWXAppInstalled()) {
                                    ToastUtil.showToast(getString(R.string.wx_installed));
                                }
                                PayReq payReq = new PayReq();
                                payReq.appId = jsonObject.optJSONObject("data").optString("appid");
                                payReq.partnerId = jsonObject.optJSONObject("data").optString("partnerid");
                                payReq.prepayId = jsonObject.optJSONObject("data").optString("prepayid");
                                payReq.packageValue = jsonObject.optJSONObject("data").optString("package");
                                payReq.nonceStr = jsonObject.optJSONObject("data").optString("noncestr");
                                payReq.timeStamp = jsonObject.optJSONObject("data").optString("timestamp");
                                payReq.extData = "coopertionPay";
                                payReq.sign = jsonObject.optJSONObject("data").optString("sign");
                                msgApi.sendReq(payReq);
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    private void payszfb(String money, String ids) {
        JsonObject payJson = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            payJson.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        payJson.addProperty("payment_mode", "3");
        payJson.addProperty("money", money);
        payJson.addProperty("type", "33");
        payJson.addProperty("ids", ids);
        XHttpRequest.getInstance().postRequests(Url.PAY, payJson.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if (!MyUtil.checkAliPayInstalled(CooperationActivity.this)) {
                                    ToastUtil.showToast(getString(R.string.zfb_installed));
                                    return;
                                }
                                Runnable payRunnable = new Runnable() {

                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(CooperationActivity.this);
                                        final Map<String, String> res = alipay.payV2(jsonObject.optJSONObject("data").optString("contents"), true);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                PayResult payResult = new PayResult(res);
                                                String resultInfo = payResult.getResult();
                                                String resultStatus = payResult.getResultStatus();
                                                if ("9000".equals(resultStatus)) {
                                                    ToastUtil.showToast(getString(R.string.pay_success));
                                                    finish();
                                                } else {
                                                    ToastUtil.showToast(getString(R.string.pay_failed));
                                                }
                                            }
                                        });
                                    }

                                };

                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (countdown != null) {
            countdown.cancel();
        }
    }


}
